<?php
namespace app\index\controller;

use app\index\model\question as QuestionModel;
use app\index\model\user as UserModel;
use app\index\model\questionImage as QuestionImageModel;
use app\index\model\noticeQuestion as NoticeQuestionModel;
use app\index\model\answer as AnswerModel;
use app\index\model\expert as ExpertModel;

use app\index\controller\JsonData;

use think\Request;
use think\Db;

class Question extends JsonData
{
    public function inAnswerTimechange($minute) 
    {
        if ($minute <= 10) {
            return $minute . "分钟";
        }
        else if ($minute <= 60) {
            return "1小时";
        }
        else {
            return $minute / 60 . "小时";
        }
    }
    
    public function dealQuestionData($questions)
    {
        //从数据库读
        $hoursClose = 72;

        foreach ($questions as $key => $value) {
            

            //处理问题还剩多少回答时间  datetime -> hours(int)
            $whenAsk = $value["whenAsk"];
            $timestamp = strtotime($whenAsk);
            $time = time();
            $questions[$key]["needAnswerTime"] = (int)(72 - ($time - $timestamp) / 3600);
            //处理第一个专家回答的时间(多长时间内抢答)
            if (array_key_exists("firstExpertAnswerInTime", $value)) {
                $questions[$key]["firstExpertAnswerInTime"] = (int)($time - $firstExpertAnswerTime) / 60;
                $questions[$key]["firstExpertAnswerInTime"] = $this->inAnswerTimechange($questions[$key]["firstExpertAnswerInTime"]);
            }
            
            
            
        }
        return $questions;
        
    }
    public function getQuestionInfo($questionToken)
    {
        $question = QuestionModel::get(["id" => $questionToken]);
        $user = UserModel::get(['userToken' => $question['askerToken']]);
        $question['askerInfo'] = $user;
        return $question;
    }
    public function findQuestionAboutInfo($question, $userToken = NULL)
    {
        foreach ($question as $key => $value) {
            if ($userToken != NULL) {
                //查询是否关注
                $questionToken = $value["id"];
                $question[$key]["isNotice"] = $this->isNoticeQuestion($questionToken, $userToken);
                //查询是否回答过
                $note = AnswerModel::get(["answererToken" => $userToken, "questionToken" => $questionToken]);
                $question[$key]["isHaveAnswer"] = $note == NULL ? false : true;
                //查询是否是本人提交的
                $question[$key]["isMineQuestion"] = $userToken == $value["askerToken"];
            }
            //获取相关答案数目
            $answerTab = "dcw_fastask_answer";
            $questionToken = $value["id"];
            $sql = "SELECT COUNT(*) AS answerNum FROM $answerTab WHERE questionToken=$questionToken";
            $allNote = Db::query($sql);
            $answerNum = $allNote[0]["answerNum"];
            $question[$key]["answerNum"] = $answerNum;
            //查询提问者信息
            $asker = UserModel::get(["userToken" => $value["askerToken"]]);
            $asker = $asker == NULL ? NULL : $asker->toArray();
            $question[$key]["askerInfo"] = $asker;
            //查询答案中第一个由专家回答的信息
            $expertTab = "dcw_fastask_expert";
            $answerTab = "dcw_fastask_answer";
            $userTab = "dcw_fastask_user";
            $questionToken = $value["id"];
            $sql = "SELECT 
                    $expertTab.*
                    FROM $expertTab,$answerTab,$userTab
                    WHERE $answerTab.questionToken=$questionToken
                    AND $answerTab.answererToken=$userTab.userToken
                    AND $userTab.isExpert=1 
                    AND $userTab.userToken=$expertTab.expertToken
                    ORDER BY $answerTab.id LIMIT 1
                    ";
            $expert = Db::query($sql);
            $question[$key]["firstAnswerExpert"] = $expert;
            //查询相关专家信息
            $expert = ExpertModel::get(["expertToken" => $value["expertToken"]]);
            $expert = $expert == NULL ? NULL : $expert->toArray();
            $question[$key]["expert"] = $expert;
            
            
        }
        return $question;
    }
    //获取一个分类的问题
    public function getKindQuestion(Request $request)
    {
        //获取参数 类别
        $userToken = $request->param("userToken");
        $kindName = $request->param("kindName");
        $lastId = $request->param("lastId");
        $dataNum = $request->param("dataNum");
        //判断是否是专家
        $isExpert = NULL;
        $expertController = controller("index/Expert");
        $isExpert = $expertController->isExpert($userToken);
        //查询数据
        $query = $lastId == 0 ? 
        function ($query) use ($dataNum, $lastId, $kindName) {
            $query->where("kindName", $kindName)->order('id', 'desc')->limit($dataNum);
        } :
        function ($query) use ($dataNum, $lastId, $kindName) {
            $query->where("kindName", $kindName)->where('id', '<', $lastId)->order('id', 'desc')->limit($dataNum);
        };
        
        $question = QuestionModel::all($query);

        //已解决的问题在前
        if ($isExpert) {
            usort($question, function ($a, $b) {
                return $a["isSolved"] ? 1 : -1;
            });
        }
        else {

        }
        //查询相关字段
        $question = $this->findQuestionAboutInfo($question, $userToken);
        //处理每个问题的数据
        $question = $this->dealQuestionData($question);
        $json = $this->getJsonData(0, "success", $question);
        return $json;
        
        
    }
    //获取已解决的问题
    public function getSolvedQuestion(Request $request)
    {
        //获取参数  lastId,dataNum 表示 最后一个问题的id，每页数据条数
        $lastId = $request->param("lastId");
        $dataNum = $request->param("dataNum");
        $code = $request->param("code");
        
        //获取用户的 token
        $Wx = controller("index/Wx");
        $userToken = md5($Wx->getOpenId($code));
        //查询数据
        $questionTab = "dcw_fastAsk_question";
        $userTab = "dcw_fastAsk_user";
        $answerTab = "dcw_fastAsk_answer";
        $expertTab = "dcw_fastAsk_expert";
        $query = $lastId == 0 ? 
        function ($query) use ($dataNum, $lastId) {
            $query->where("isSolved", 1)->order('id', 'desc')->limit($dataNum);
        } :
        function ($query) use ($dataNum, $lastId) {
            $query->where("isSolved", 1)->where('id', '<', $lastId)->order('id', 'desc')->limit($dataNum);
        };

        $question = QuestionModel::all($query);
        //查询相关字段
        $question = $this->findQuestionAboutInfo($question, $userToken);
        //处理每个问题的数据
        $question = $this->dealQuestionData($question);

        //查询用户的头像，昵称，暂存
        $userController = controller("index/User");
        $mineController = controller("index/Mine");
        $findRes = $userController->getUserInfo($userToken);
        //查询用户的专家认证状态
        $certifyStatus = controller("index/expert")->certifyStatus($userToken);

        $json = $this->getJsonData(0, "success", array(
            'question' => $question,
            'userToken' => $userToken,
            'avatarUrl' => $findRes["avatarUrl"],
            'nickName' => $findRes['nickName'],
            "certifyStatus" => $certifyStatus,
            "questionAboutNum" => $mineController->getAboutQuestionNumNoReq($userToken)[0]
        ));
        return $json;
        
    }   
    public function saveQuestion($question)
    {
        $message = "";
        if ($question->isUpdate(false)->save()) {
            $message .= "add question success.";
        }
        else {
            $message .= "add question fail.";
        }
        return $message;
    }
    //新增问题
    public function addNewQuestion(Request $request) 
    {
        //获取参数 存放 dcw_fastAsk_question表
        $kindName = $request->param("kindName");
        $payPrice = $request->param("payPrice");
        $whenAsk = $request->param("whenAsk");
        $questionContent = $request->param("questionContent");
        $isAnonymous = $request->param("isAnonymous");
        $isPublic = $request->param("isPublic");
        $isAskExpert = $request->param("isAskExpert");
        $expertToken = $request->param("expertToken");

        //存放 dcw_fastAsk_user表
        $userAvatar = $request->param("userAvatar");
        $userName = $request->param("userName");
        $code = $request->param("code");            //微信获取 openid 的code

        //存放 dcw_fastAsk_questionImage
        $photoes = $request->param("photoes");
        $photoes = json_decode($photoes, true);


        //创建问题模型
        $question = new QuestionModel;
        $question->kindName = $kindName;
        $question->payPrice = $payPrice;
        $question->whenAsk = $whenAsk;
        $question->questionContent = $questionContent;
        $question->isAnonymous = $isAnonymous;
        $question->isPublic = $isPublic;
        $question->isAskExpert = $isAskExpert;
        $question->expertToken = $expertToken;

        //创建用户模型
        $wx = controller("index/Wx");
        $openId = $wx->getOpenId($code);
        $userToken = md5($openId);
        $question->askerToken = $userToken;

        $message = "";
        
        //保存 openid 和 userToken 之间的映射
        $userTokenController = controller("index/UserToken");
        $message .= $userTokenController->saveUserToken($openId, $userToken);

        //新增问题
        $message .= $this->saveQuestion($question);

        //创建用户模型
        $user = new UserModel;
        $user->userAvatar = $userAvatar;
        $user->userName = $userName;
        $user->userToken = $userToken;
        $userController = controller("index/User");
        $message .= $userController->saveUser($user);

        //创建图片模型
        $questionImageController = controller("index/QuestionImage");
        $questionImage = new QuestionImageModel;
        $photoList = [];
        foreach ($photoes as $key => $value) {
            $photoList[] = [
                "questionToken" => $question['id'],
                "imgUrl" => $value["imgUrl"]
            ];
        }
        $message .= $questionImageController->saveQuestionImage($questionImage, $photoList);

        //返回问题的信息
        $resQuestion = $this->getQuestionInfo($question["id"]);
        $json = $this->getJsonData(0, $message, $resQuestion);
        return $json;
        
    }
    public function isNoticeQuestion($questionToken, $userToken)
    {
        
        //查询
        $noticeQuestion = NoticeQuestionModel::get(["userToken" => $userToken, "questionToken" => $questionToken]);
        $isNotice = $noticeQuestion == NULL ? false : true;

        return $isNotice;
    }
    public function getIsNoticeQuestion(Request $request)
    {
        //获取请求参数
        $questionToken = $request->param("questionToken");
        $userToken = $request->param("userToken");

        $isNotice = $this->isNoticeQuestion($questionToken, $userToken);

        //返回消息
        $JsonData = controller("index/JsonData");
        $json = $JsonData->getJsonData(0, "get isNotice success.", array(
            "isNotice" => $isNotice
        ));
        return $json;
    }
    public function noticeQuestion(Request $request)
    {
        //获取请求参数
        $questionToken = $request->param("questionToken");
        $userToken = $request->param("userToken");
        $isNotice = $request->param("isNotice");

        $message = NULL;
        //查询是否存在该数据
        $noticeQuestion = NoticeQuestionModel::get(["questionToken" => $questionToken, "userToken" => $userToken]);
        if ($isNotice) {
            //关注 -> 添加数据
            if ($noticeQuestion == NULL) {
                //添加
                $newNotice = new NoticeQuestionModel;
                $newNotice->questionToken = $questionToken;
                $newNotice->userToken = $userToken;
                $newNotice->save();
            }
            else {

            }
            $message = "notice question success.";
        }
        else {
            //取消关注 -> 删除数据
            if ($noticeQuestion == NULL) {

            }
            else {
                //删除
                $noticeQuestion->delete();
            }
            $message = "cancel notice question success.";
        }

        //返回消息
        $JsonData = controller("index/JsonData");
        $json = $JsonData->getJsonData(0, $message, array());
        return $json;
    }
    
}